package com.leyou.user.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.common.exceptions.LyException;
import com.leyou.common.utils.RegexUtils;
import com.leyou.user.config.PasswordConfig;
import com.leyou.user.dto.UserDTO;
import com.leyou.user.entity.User;
import com.leyou.user.mapper.UserMapper;
import com.leyou.user.service.UserService;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;

import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.leyou.common.constants.MQConstants.ExchangeConstants.SMS_EXCHANGE_NAME;
import static com.leyou.common.constants.MQConstants.RoutingKeyConstants.VERIFY_CODE_KEY;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private AmqpTemplate amqpTemplate;

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    private static final String KEY_PREFIX = "user:verify:code:";

    @Transactional
    @Override
    public Boolean DataTypeExists(String data, Integer type) {
        //判断数据类型是否正确
        if (type != 1 && type != 2){
            throw new LyException(400, "参数类型错误！");
        }
        //条件查询
        Integer count = query()
                .eq(type == 1, "username", data)
                .eq(type == 2, "phone", data).count();
        //返回数据是否存在
        return count != 0;
    }

    @Override
    public void sendCode(String phone) {
        //校验手机号码格式
        if (!RegexUtils.isPhone(phone)){
            throw new LyException(400 , "手机格式错误");
        }
        //随机生成一个验证码
        String code = RandomStringUtils.randomNumeric(6);
        //发送短信
        //将数据封装到个map集合中
        Map<String,String> map = new HashMap<>();
        map.put("phone", phone);
        map.put("code", code);
        amqpTemplate.convertAndSend(SMS_EXCHANGE_NAME, VERIFY_CODE_KEY, map);
        //将数据存到redis
        redisTemplate.opsForValue().set(KEY_PREFIX + phone, code ,5, TimeUnit.MINUTES);
    }

    @Override
    public void register(User user, String code) {
        //校验验证码
        String lookCode = redisTemplate.opsForValue().get(KEY_PREFIX + user.getPhone());
        //比较验证码
        if (!StringUtils.equals(code,lookCode)){
            throw new LyException(400 , "验证码错误");
        }
        //密码加密
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        //将数据添加到数据库
        save(user);
    }

    @Override
    public UserDTO queryUserByUsernameAndPassword(String username, String password) {
        //用户名查询
        User user = query().eq("username", username).one();
        //判断用户是否存在
        if (user == null){
            throw new LyException(400 ,"用户名或密码错误！");
        }
        //用户名正确后再查询密码
        if (!passwordEncoder.matches(password,user.getPassword())){
            throw new LyException(400 ,"用户名或密码错误！");
        }
        //类型转换后返回
        return new UserDTO(user);
    }
}
